package com.shuzi.MediaShare.gui.movie;

import io.vov.vitamio.LibsChecker;
import io.vov.vitamio.widget.VideoView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.shuzi.MediaShare.Constant;
import com.shuzi.MediaShare.R;
import com.shuzi.MediaShare.base.BaseFrameAtivity;
import com.shuzi.MediaShare.download.DownloadInfo;
import com.shuzi.MediaShare.download.DownloadManager;
import com.shuzi.MediaShare.gui.DetailViewPagerAdapter;
import com.shuzi.MediaShare.model.ChargeInfo;
import com.shuzi.MediaShare.model.MediaDownLoadLinkInfo;
import com.shuzi.MediaShare.model.MovieInfo;
import com.shuzi.MediaShare.net.Protocol;
import com.shuzi.MediaShare.view.AutoLineFeed;
import com.shuzi.MediaShare.view.MyVideoView;
import com.viewpagerindicator.UnderlinePageIndicator;

/**
 * 播放视图类
 * 
 * @author lung 下午9:33:48 2013
 */
public class MovieDetailPlayerActivity extends BaseFrameAtivity implements
		OnClickListener
{

	/** 播放地址 */
	private String url = "";

	private MyVideoView myVideoView;

	private RelativeLayout.LayoutParams portParams = null;

	private RelativeLayout.LayoutParams landParams = null;

	/** 电影下载地址集数 */
	private List<MediaDownLoadLinkInfo> mediaDownLoadLinkInfos;

	private DetailViewPagerAdapter adapter;

	private MovieInfo movieInfo = null;

	private ViewPager viewPager;

	private String downloadPath = "";

	private UnderlinePageIndicator underlinePageIndicator;

	/** 简介 */
	private TextView detailInfoTextView;

	/** 下载 */
	private TextView downloadTextView;

	/** 播放 */
	private TextView playTextView;

	/** 加载电影详情信息 */
	private final int LOAD_MEDIADOWNLOADLINKINFO = 0;

	/** 扣费 */
	private final int CHARGE = 1;

	private DownloadManager downloadManager;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		downloadManager = DownloadManager.getInstace();
		if (!LibsChecker.checkVitamioLibs(this))
			return;
		loadData(LOAD_MEDIADOWNLOADLINKINFO);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE
				&& myVideoView.videoView != null)
		{
			setFullScreen();
			myVideoView.setLayoutParams(landParams);
			myVideoView.videoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE,
					myVideoView.VideoAspectRatio);
			titileBarLayout.setVisibility(View.GONE);

		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT
				&& myVideoView.videoView != null)
		{
			quitFullScreen();
			myVideoView.setLayoutParams(portParams);
			myVideoView.videoView.setVideoLayout(VideoView.VIDEO_LAYOUT_ORIGIN,
					0);
			titileBarLayout.setVisibility(View.VISIBLE);
		}
		super.onConfigurationChanged(newConfig);

	}

	@Override
	protected boolean initData(Integer... params)
	{
		boolean isSuccess = true;
		// 获取详情
		if (params[0] == LOAD_MEDIADOWNLOADLINKINFO)
		{
			mediaDownLoadLinkInfos = Protocol.queryVideo(movieInfo.getType(),
					movieInfo.getID());
			if (mediaDownLoadLinkInfos != null
					&& mediaDownLoadLinkInfos.size() == 0)
			{
				isSuccess = false;
			}
		} else if (params[0] == CHARGE)
		{
			// Protocol.chargeCell(type, videoId)
		}

		return isSuccess;
	}

	@Override
	protected void refreshView(boolean isSuccessful, Integer... params)
	{
		switch (params[0])
		{
		// 获取详情
		case LOAD_MEDIADOWNLOADLINKINFO:
			if (isSuccessful)
			{
				adapter = new DetailViewPagerAdapter(getDetailViewList());
				if (mediaDownLoadLinkInfos != null
						&& mediaDownLoadLinkInfos.size() != 0)
				{
					url = Protocol.BASEPATH
							+ mediaDownLoadLinkInfos.get(0).getFilepath();
					downloadPath = mediaDownLoadLinkInfos.get(0).getFilepath();
					myVideoView.startPlayVideo(this, url);
					viewPager.setAdapter(adapter);
					underlinePageIndicator.setViewPager(viewPager);
					underlinePageIndicator.setFades(false);
				}
			} else
			{
				Toast.makeText(this, "暂无详情信息", Toast.LENGTH_SHORT).show();
				finish();
			}
			break;

		default:
			break;
		}

	}

	@Override
	protected void tryAgain()
	{
		loadData();
	}

	@Override
	protected View setCenterView()
	{
		movieInfo = (MovieInfo) getIntent().getSerializableExtra("MOVIEINFO");
		View view = View.inflate(this, R.layout.movie_detail_play, null);
		myVideoView = (MyVideoView) view.findViewById(R.id.myVideoView);
		RelativeLayout.LayoutParams params = (LayoutParams) myVideoView
				.getLayoutParams();
		params.height = Constant.HEIGHT / 3;
		myVideoView.setLayoutParams(params);
		underlinePageIndicator = (UnderlinePageIndicator) view
				.findViewById(R.id.underlinePageIndicator1);
		portParams = (LayoutParams) myVideoView.getLayoutParams();
		landParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT,
				RelativeLayout.LayoutParams.MATCH_PARENT);
		viewPager = (ViewPager) view.findViewById(R.id.movie_viewpager);
		detailInfoTextView = (TextView) view.findViewById(R.id.detail_info);
		downloadTextView = (TextView) view.findViewById(R.id.download_text);
		playTextView = (TextView) view.findViewById(R.id.play_text);
		detailInfoTextView.setOnClickListener(this);
		downloadTextView.setOnClickListener(this);
		playTextView.setOnClickListener(this);

		return view;
	}

	/**
	 * 获取详情分类视图
	 * 
	 * @return
	 */
	private List<View> getDetailViewList()
	{
		List<View> list = new ArrayList<View>();
		TextView summary = new TextView(this);
		summary.setText(movieInfo.getSummary());
		summary.setTextColor(Color.BLACK);

		AutoLineFeed autoLineFeed = new AutoLineFeed(this);
		int count = mediaDownLoadLinkInfos.size();
		for (int i = 0; i < count; i++)
		{
			Button downloadButton = new Button(this);
			mediaDownLoadLinkInfos.get(i).setOrder(i + 1);
			if (mediaDownLoadLinkInfos.get(i).getCharpter() == null)
			{

				mediaDownLoadLinkInfos.get(i).setCharpter((i + 1) + "");
			} else
			{
				if (mediaDownLoadLinkInfos.get(i).getCharpter().equals("null")
						|| mediaDownLoadLinkInfos.get(i).getCharpter()
								.equals(""))
				{
					mediaDownLoadLinkInfos.get(i).setCharpter((i + 1) + "");
				}
			}
			downloadButton.setText(movieInfo.getName_cn()
					+ mediaDownLoadLinkInfos.get(i).getCharpter());
			downloadButton.setTag(mediaDownLoadLinkInfos.get(i));
			downloadButton.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					final MediaDownLoadLinkInfo mediaDownLoadLinkInfo = (MediaDownLoadLinkInfo) v
							.getTag();

					new Thread(new Runnable()
					{

						@Override
						public void run()
						{
							// 检测有没有存在下载任务
							if (downloadManager
									.getDownloadInfo(mediaDownLoadLinkInfo
											.getName()
											+ mediaDownLoadLinkInfo
													.getCharpter()
											+ mediaDownLoadLinkInfo.getOrder()) != null)
							{
								MovieDetailPlayerActivity.this
										.runOnUiThread(new Runnable()
										{
											public void run()
											{
												Toast.makeText(
														MovieDetailPlayerActivity.this,
														"任务已经在下载列表，请查看",
														Toast.LENGTH_SHORT)
														.show();
											}
										});

								return;
							}

							// 判断是否已经下载，已经下载则不下载，直接提示

							File oldFile = new File(downloadManager
									.getBasePath(), mediaDownLoadLinkInfo
									.getName()
									+ mediaDownLoadLinkInfo.getCharpter()
									+ ".mp4");
							if (oldFile.exists())
							{
								MovieDetailPlayerActivity.this
										.runOnUiThread(new Runnable()
										{
											public void run()
											{
												Toast.makeText(
														MovieDetailPlayerActivity.this,
														"你已下载，请在下载管理里面查看",
														Toast.LENGTH_SHORT)
														.show();
											}
										});

								return;
							}

							// 判断余额是否足够
							final ChargeInfo info = Protocol.chargeCell(
									movieInfo.getType(),
									mediaDownLoadLinkInfo.getID());

							if (info != null && info.getCode().equals("0"))
							{
								MovieDetailPlayerActivity.this
										.runOnUiThread(new Runnable()
										{
											public void run()
											{
												Toast.makeText(
														MovieDetailPlayerActivity.this,
														"下载扣除"
																+ info.getFee()
																+ "元,你的余额为"
																+ info.getBalance()
																+ "元",
														Toast.LENGTH_LONG)
														.show();
												DownloadInfo info = new DownloadInfo(
														mediaDownLoadLinkInfo
																.getName()
																+ mediaDownLoadLinkInfo
																		.getCharpter(),
														Protocol.BASEPATH
																+ mediaDownLoadLinkInfo
																		.getFilepath(),
														mediaDownLoadLinkInfo
																.getName()
																+ mediaDownLoadLinkInfo
																		.getCharpter()
																+ mediaDownLoadLinkInfo
																		.getOrder());
												com.shuzi.MediaShare.download.DownloadManager
														.getInstace()
														.addDownloadInfoAndStart(
																info);
											}
										});
							} else
							{
								MovieDetailPlayerActivity.this
										.runOnUiThread(new Runnable()
										{
											public void run()
											{
												Toast.makeText(
														MovieDetailPlayerActivity.this,
														"余额不足，请去设置里面充值。",
														Toast.LENGTH_LONG)
														.show();
											}
										});

							}

						}
					}).start();

				}
			});
			autoLineFeed.addView(downloadButton);
		}

		AutoLineFeed autoLineFeedPlay = new AutoLineFeed(this);
		// int count2 = mediaDownLoadLinkInfos.size();
		for (int i = 0; i < count; i++)
		{
			Button downloadButton = new Button(this);
			if (mediaDownLoadLinkInfos.get(i).getCharpter() == null)
			{
				mediaDownLoadLinkInfos.get(i).setCharpter((i + 1) + "");
			} else
			{
				if (mediaDownLoadLinkInfos.get(i).getCharpter().equals("null")
						|| mediaDownLoadLinkInfos.get(i).getCharpter()
								.equals(""))
				{
					mediaDownLoadLinkInfos.get(i).setCharpter((i + 1) + "");
				}
			}
			downloadButton.setText(movieInfo.getName_cn()
					+ mediaDownLoadLinkInfos.get(i).getCharpter());
			downloadButton.setTag(mediaDownLoadLinkInfos.get(i));
			downloadButton.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					MediaDownLoadLinkInfo mediaDownLoadLinkInfo = (MediaDownLoadLinkInfo) v
							.getTag();
					myVideoView.startPlayVideo(
							MovieDetailPlayerActivity.this,
							Protocol.BASEPATH
									+ mediaDownLoadLinkInfo.getFilepath());
				}
			});
			autoLineFeedPlay.addView(downloadButton);
		}

		// linearLayout.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL);
		list.add(summary);
		list.add(autoLineFeed);
		list.add(autoLineFeedPlay);

		return list;
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.detail_info:
			viewPager.setCurrentItem(0);
			break;

		case R.id.download_text:
			viewPager.setCurrentItem(1);
			break;

		case R.id.play_text:
			viewPager.setCurrentItem(2);
			break;

		}

	}
}
